﻿using AutoMapper;
using D.B.Data.API.Applications.Command.LeaveCommand;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Output;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.LeaveCommandHandler
{
    public class GetOneUserLeaveCommandHandler : IRequestHandler<GetOneUserLeaveCommand, APIPaging<QueryUserLeaveDTO>>
    {
        private readonly IBaseRepository<WorkflowModel> baseRepository;
        private readonly IBaseRepository<DeptModel> deptRepository;
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IMapper mapper;
        public GetOneUserLeaveCommandHandler(IBaseRepository<WorkflowModel> baseRepository, IMapper mapper, IBaseRepository<DeptModel> deptRepository, IBaseRepository<UserModel> userRepository)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.deptRepository = deptRepository;
            this.userRepository = userRepository;
        }

        public Task<APIPaging<QueryUserLeaveDTO>> Handle(GetOneUserLeaveCommand request, CancellationToken cancellationToken)
        {

            var res = baseRepository.GetAll().Where(s => s.UserId== request.UserId && s.LeaveTIme.Year == request.Year && s.LeaveTIme.Month == request.Month && !s.IsDel&&s.State).ToList();
            var DeptId = userRepository.GetAll().FirstOrDefault(s => s.Id == request.UserId).DeptId;


            var model = mapper.Map<List<QueryUserLeaveDTO>>(res);
            foreach (var item in model)
            {
               
              item.DeptName = deptRepository.GetAll().FirstOrDefault(s => s.Id == DeptId).DeptName;

            }


            var count = model.Count();

            model = model.OrderBy(s => s.LeaveTIme.Month).ThenBy(s => s.LeaveTIme.Day).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            APIPaging<QueryUserLeaveDTO> aPIPaging = new APIPaging<QueryUserLeaveDTO>()
            {
                Code = EnumCode.Ok,
                Count = count,
                PageData = model

            };

            return Task.FromResult(aPIPaging);
        }
    }
}
